/**
 * @file
 * @description 对axios进行二次封装的文件
 */


import axios from 'axios';
import Message from "element-ui"
import store from "@/store"

axios.defaults.baseURL = "/shi"; //基地址
axios.defaults.timeout = process.env.VUE_APP_TIMEOUT;  //超时时间

/**
 * 请求拦截器
 */
axios.interceptors.request.use(config => {
    config.headers.Authorization = store.getters.token
    return config
},error => Promise.reject(error))

/**
 * 响应式拦截器
 */
axios.interceptors.response.use(response => {
    const {data,meta:{
        msg,
        status
    }}=response.data;
    if(status === 200 || status === 201){
        return data
    }
    Message.error(msg)
    return Promise.reject(msg)
}), error =>{
    const msg = error.toString();
    if(msg.includes("Network Error")){
        Message.error("请求失败，请检查您的网络是否正常");
        return Promise.reject(error)
    }
    if(msg.includes("Timeout")){
        Message.error("请求超时,请稍后再试");
        return Promise.reject(error)
    }

    const { status } = error.response ; 
    switch (status) {
        case 404:
            Message.error("接口不存在")
            break;
        case 500:
            Message.error("接口请求失败")
            break;
        case 401:
            Message.error("身份验证失败，请稍后再试")
            break;
        default :
            Message.error("未知错误");
            break;
    }
    return Promise.reject(error) 
}

export default axios

